#!/bin/bash

# 一键启动旅行预订应用服务脚本
set -e  # 遇到错误立即退出

echo "========================================"
echo "   旅行预订应用一键启动脚本"
echo "========================================"

# 定义颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 检查使用哪个docker compose命令（提前检测）
check_docker_compose_command() {
    if command -v docker &> /dev/null && docker compose version &> /dev/null; then
        COMPOSE_CMD="docker compose"
        echo -e "${GREEN}✓ 使用 docker compose 命令${NC}"
    elif command -v docker-compose &> /dev/null; then
        COMPOSE_CMD="docker-compose"
        echo -e "${GREEN}✓ 使用 docker-compose 命令${NC}"
    else
        echo -e "${RED}错误: 未找到可用的docker compose命令${NC}"
        echo -e "${YELLOW}请安装 Docker Compose:${NC}"
        echo -e "  https://docs.docker.com/compose/install/"
        exit 1
    fi
}

# 检查Docker是否运行
check_docker() {
    if ! command -v docker &> /dev/null; then
        echo -e "${RED}错误: Docker未安装，请先安装Docker${NC}"
        exit 1
    fi

    if ! docker info &> /dev/null; then
        echo -e "${RED}错误: Docker守护进程未运行，请启动Docker${NC}"
        exit 1
    fi
    echo -e "${GREEN}✓ Docker检查通过${NC}"
}

# 检查必要文件
check_required_files() {
    local missing_files=()
    
    # 检查必要的文件
    if [ ! -f "docker-compose.yml" ]; then
        missing_files+=("docker-compose.yml")
    fi
    
    if [ ! -d "mysql" ]; then
        missing_files+=("mysql目录")
    fi
    
    if [ ! -f "mysql/init.sql" ]; then
        missing_files+=("mysql/init.sql")
    fi
    
    if [ ${#missing_files[@]} -ne 0 ]; then
        echo -e "${RED}错误: 缺少必要文件: ${missing_files[*]}${NC}"
        echo -e "${YELLOW}请确保在项目根目录运行此脚本${NC}"
        exit 1
    fi
    
    echo -e "${GREEN}✓ 必要文件检查通过${NC}"
}

# 检查镜像文件是否存在
check_image_file() {
    if [ ! -f "TR-App.tar" ]; then
        echo -e "${YELLOW}警告: TR-App.tar 镜像文件不存在，跳过加载镜像步骤${NC}"
        return 1
    fi
    echo -e "${GREEN}✓ 找到镜像文件 TR-App.tar${NC}"
    return 0
}

# 加载Docker镜像
load_image() {
    echo "加载Docker镜像..."
    if docker load -i TR-App.tar; then
        echo -e "${GREEN}✓ 镜像加载成功${NC}"
    else
        echo -e "${RED}错误: 镜像加载失败${NC}"
        exit 1
    fi
}

# 启动Docker服务
start_services() {
    echo "启动Docker服务..."
    
    if $COMPOSE_CMD up -d; then
        echo -e "${GREEN}✓ 服务启动成功${NC}"
    else
        echo -e "${RED}错误: 服务启动失败${NC}"
        echo -e "${YELLOW}尝试诊断问题...${NC}"
        diagnose_problem
        exit 1
    fi
}

# 诊断问题
diagnose_problem() {
    echo -e "${YELLOW}=== 问题诊断 ===${NC}"
    
    # 检查容器状态
    echo -e "${YELLOW}容器状态:${NC}"
    $COMPOSE_CMD ps
    
    # 检查日志
    echo -e "${YELLOW}最近日志:${NC}"
    $COMPOSE_CMD logs --tail=20
    
    # 检查端口占用
    echo -e "${YELLOW}端口检查:${NC}"
    if netstat -tuln | grep -E ':16120|:16121|:16122' &> /dev/null; then
        echo -e "${RED}端口可能被占用:${NC}"
        netstat -tuln | grep -E ':16120|:16121|:16122'
    fi
}

# 等待服务就绪
wait_for_services() {
    echo "等待服务启动..."
    local max_wait=60
    local wait_time=0
    
    # 等待MySQL就绪
    echo -e "${YELLOW}等待MySQL数据库就绪...${NC}"
    while [ $wait_time -lt $max_wait ]; do
        if $COMPOSE_CMD exec mysql mysqladmin ping -h localhost -u root -proot --silent 2>/dev/null; then
            echo -e "${GREEN}✓ MySQL数据库就绪${NC}"
            break
        else
            echo -n "."
            sleep 3
            ((wait_time+=3))
        fi
    done
    
    if [ $wait_time -ge $max_wait ]; then
        echo -e "${YELLOW}⚠ MySQL启动超时，但继续流程...${NC}"
    fi
    
    # 等待应用就绪
    wait_time=0
    echo -e "${YELLOW}等待应用服务就绪...${NC}"
    while [ $wait_time -lt $max_wait ]; do
        if $COMPOSE_CMD ps | grep tr-app | grep Up &> /dev/null; then
            echo -e "${GREEN}✓ 应用服务就绪${NC}"
            break
        else
            echo -n "."
            sleep 3
            ((wait_time+=3))
        fi
    done
    
    if [ $wait_time -ge $max_wait ]; then
        echo -e "${YELLOW}⚠ 应用启动超时，但继续流程...${NC}"
    fi
}

# 显示服务状态
show_status() {
    echo ""
    echo "========================================"
    echo "           服务状态信息"
    echo "========================================"

    # 显示容器状态
    echo -e "${YELLOW}容器状态:${NC}"
    $COMPOSE_CMD ps

    echo ""
    echo -e "${YELLOW}服务访问地址:${NC}"
    echo -e "前端界面: ${GREEN}http://localhost:16121${NC}"
    echo -e "后端API:  ${GREEN}http://localhost:16120${NC}"
    echo -e "MySQL数据库: ${GREEN}localhost:16122${NC}"
    echo -e "前端用户: user"
    echo -e "前端用户密码: 1234"    
    echo -e "前端admin: admin"
    echo -e "前端admin密码: 1234"
    echo -e "MySQL用户: root"
    echo -e "MySQL密码: root"

    echo ""
    echo -e "${YELLOW}常用命令:${NC}"
    echo -e "查看日志:   ${GREEN}$COMPOSE_CMD logs${NC}"
    echo -e "停止服务:   ${GREEN}$COMPOSE_CMD down${NC}"
    echo -e "重启服务:   ${GREEN}$COMPOSE_CMD restart${NC}"
    echo -e "查看详细日志: ${GREEN}$COMPOSE_CMD logs -f${NC}"
}

# 主执行流程
main() {
    echo "开始启动服务..."
    echo ""

    # 提前检查docker compose命令
    check_docker_compose_command
    
    # 执行检查
    check_docker
    check_required_files

    # 加载镜像（如果存在）
    if check_image_file; then
        load_image
    fi

    # 启动服务
    start_services

    # 等待服务就绪
    wait_for_services

    # 显示状态信息
    show_status

    echo ""
    echo -e "${GREEN}✅ 服务启动完成！${NC}"
    echo -e "请访问 ${GREEN}http://localhost:16121${NC} 使用应用"
    echo ""
    echo -e "${YELLOW}如果遇到问题，可以运行以下命令查看详细日志:${NC}"
    echo -e "$COMPOSE_CMD logs -f"
}

# 执行主函数
main "$@"